/***************************************************************************
 *
 *   copyright            : (C) 2005 Winds of Storm
 *
 *   $Id: logging.c,v 1.3 2005/12/13 21:06:32 nathan Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#include "sb.h"

extern FILE *logfile;

int sb_log(int prio, char *fmt, ...) {
	va_list	ap;
	time_t	now;
	//char	datetime[16];	/* enough room for ... MMM DD TT:TT:TT */

	va_start(ap, fmt);

#ifndef SYSLOG_ALWAYS
	if (logfile) {
		now = time(0);
		//cftime(datetime, "%b %d %T", &now);
		//fprintf(logfile, "%s [PID %d]", datetime, (int) getpid());
		fprintf(logfile, "[PID %d]", (int) getpid());
		switch(prio & 7) {
			case(LOG_EMERG):	fprintf(logfile,	"[EMERG] ");	break;
			case(LOG_ALERT):	fprintf(logfile,	"[ALERT] ");	break;
			case(LOG_CRIT):		fprintf(logfile,	"[CRIT] ");	break;
			case(LOG_ERR):		fprintf(logfile,	"[ERR] ");	break;
			case(LOG_WARNING):	fprintf(logfile,	"[WARNING] ");	break;
			case(LOG_NOTICE):	fprintf(logfile,	"[NOTICE] ");	break;
			case(LOG_INFO):		fprintf(logfile,	"[INFO] ");	break;
			case(LOG_DEBUG):	fprintf(logfile,	"[DEBUG] ");	break;
			default:		fprintf(logfile,	"[NONE] ");
		}
		vfprintf(logfile, fmt, ap);
		fprintf(logfile, "\n");
		fflush(logfile);
	} else {
#else
	{
#endif
		vsyslog(prio, fmt, ap);
	}

	va_end(ap);
	return(0);
}

void bootstrap_logging (char *log_filename) {
	if (strcmp(log_filename, "-") == 0) {
		if ((logfile = fdopen(STDERR_FILENO, "w")) == NULL) {
			fprintf(stderr, "Couldn't open FD for stderr!\n");
			exit(1);
		}
	} else {
		if ((logfile = fopen(log_filename, "a")) == NULL) {
			fprintf(stderr, "Couldn't open FD for %s!\n", log_filename);
			exit(1);
		}
	}
}
